//
//  NoteListTableViewController.m
//  OrangeNote
//
//  Created by 刘崇龙 on 16/1/21.
//  Copyright © 2016年 崇龙. All rights reserved.
//

#import "NoteListTableViewController.h"
#import "NoteModel.h"
#import "NoteListTableViewCell.h"
#import "NoteDetailViewController.h"
#import "SphereMenu.h"
#import "LoginViewController.h"
#import "LocalDataManager.h"

#define kXXX  [UIScreen mainScreen].bounds.size.width/2
#define kYYY  [UIScreen mainScreen].bounds.size.height-100
@interface NoteListTableViewController ()<SphereMenuDelegate,UITableViewDataSource,UITableViewDelegate>


@property(nonatomic,strong)NSURL *recordAudioUrl;// 音频路径

@property(nonatomic,strong)NSMutableArray *noteArray;
@property(nonatomic,strong)NSString *bookID;
@end

NSString *NoteListTableViewCellIdentifier = @"NoteListTableViewCellIdentifier";

@implementation NoteListTableViewController


-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    self.tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:_tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"NoteListTableViewCell" bundle:nil] forCellReuseIdentifier:NoteListTableViewCellIdentifier];
    
    
    
#pragma mark    --- 加号按钮
    UIImage *startImage = [UIImage imageNamed:@"start"];

//    UIImage *image1 = [UIImage imageNamed:@"naozhong"];
//    UIImage *image2 = [UIImage imageNamed:@"luyin"];
//    UIImage *image3 = [UIImage imageNamed:@"huatuban"];
//    NSArray *images = @[image1,image2,image3];
    // 改的
    UIImage *image1 = [UIImage imageNamed:@"jiahao"];
    NSArray *imagess = @[image1];
    
        SphereMenu *sphereMenu = [[SphereMenu alloc] initWithStartPoint:CGPointMake(kXXX, kYYY)
                                                             startImage:startImage
                                                          submenuImages:imagess];
        sphereMenu.delegate = self;
        [self.view addSubview:sphereMenu];
    
    
#pragma mark===============添加笔记按钮===============
//    NoteModel *model = [NoteModel new];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style: UIBarButtonItemStyleDone target:self action:@selector(addNoteToDB)];
    
    
    _bookID = _notebookid;
    _noteArray = [NSMutableArray array];
    _noteArray = [[LocalDataManager sharedDataBase] orderAllNoteByDescWithNotebookID:_bookID];
    

        self.navigationItem.titleView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"biaotilan"]];
    
    
}

//-(void)viewDidLoad{
//    [super viewDidLoad];
//    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunched"] ) {
//        [self addNoteToDB];
//    }
//
//}

#pragma mark ===========创建新的笔记到数据库=============
-(void)addNoteToDB{
    
    NoteDetailViewController *detail = [NoteDetailViewController new];
     //notebookID 传到下个页面
    detail.bookID = _bookID;

    detail.saveNoteUpdate = ^(){
        [self.tableView reloadData];
    };
    
    [self.navigationController showViewController:detail sender:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _noteArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NoteListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NoteListTableViewCellIdentifier forIndexPath:indexPath];

    NoteModel *note = _noteArray[indexPath.row];
    cell.model = note;
    
    //将 html 语言传化成 text 形式
    NSString *content = note.content;
    NSString *str = [self filterHTML:content];
    cell.nameLabel.text = note.name;
    cell.contentLabel.text = str;
 
    CGFloat height = [self textHeight:note.content];
    [cell changeContentLabelHeight:height];
    return cell;
}

//html 语言转 text
-(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }

    return html;
}

//属性传值
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NoteDetailViewController *detail = [NoteDetailViewController new];
   //展示的 model 对象
    detail.note = _noteArray[indexPath.row];
    detail.noteListUpdate = ^(){
        [self.tableView reloadData];
    };
     UINavigationController * navigation = [[UINavigationController alloc]initWithRootViewController:detail];
    [self.navigationController presentViewController:navigation animated:YES completion:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (CGFloat)textHeight:(NSString *)string{
    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width - 20, 999);
    CGRect rect = [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} context:nil];
    return rect.size.height;
}


#pragma mark    -- 加号俩方法
- (void)sphereDidSelected:(int)index
{
    if (index == 0) {

        LoginViewController *logVC = [LoginViewController new];
//        [self.navigationController pushViewController:logVC animated:YES];
        [self addNoteToDB];
    }else if (index == 1){

        [self addNoteToDB];
        
//        AudioViewController *logVC = [AudioViewController new];
////        [logVC viewDidLoad];
//        _recordAudioUrl = logVC.recordUrl;
//        [self.navigationController pushViewController:logVC animated:YES];
    }else if (index == 2){
//        LoginViewController *logVC = [LoginViewController new];
//        [self.navigationController pushViewController:logVC animated:YES];

//        LoginViewController *logVC = [LoginViewController new];
//        [self.navigationController pushViewController:logVC animated:YES];
     
        
        
        
#pragma  mark   跳转到添加笔记

        
        
        [self addNoteToDB];
        
        
        
    }
//    }else if (index == 1){
//#pragma mark    跳转到录音
//        AudioViewController *logVC = [AudioViewController new];
////        [logVC viewDidLoad];
//        _recordAudioUrl = logVC.recordUrl;
//        
//        
//        [self.navigationController pushViewController:logVC animated:YES];
//    }else if (index == 2){
//#pragma mark    跳转到画图板
////        LoginViewController *logVC = [LoginViewController new];
////        [self.navigationController pushViewController:logVC animated:YES];
//    }
//    LoginViewController *logVC = [LoginViewController new];
//    [self.navigationController pushViewController:logVC animated:YES];
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {

    return YES;
}



- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        NoteModel *model = _noteArray[indexPath.row] ;
        [[LocalDataManager sharedDataBase] deleteNoteWithNoteID:model.ID];
          [_noteArray removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        
    }   
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
